package com.yuhong.springbootinit.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yuhong.springbootinit.common.BaseResponse;
import com.yuhong.springbootinit.common.ErrorCode;
import com.yuhong.springbootinit.common.ResultUtils;
import com.yuhong.springbootinit.exception.BusinessException;
import com.yuhong.springbootinit.exception.ThrowUtils;
import com.yuhong.springbootinit.model.dto.profile.ProfileEditRequest;
import com.yuhong.springbootinit.model.dto.profile.ProfileQueryRequest;
import com.yuhong.springbootinit.model.entity.Profile;
import com.yuhong.springbootinit.model.entity.User;
import com.yuhong.springbootinit.model.entity.UserProfile;
import com.yuhong.springbootinit.model.vo.ProfileVO;
import com.yuhong.springbootinit.service.ProfileService;
import com.yuhong.springbootinit.service.UserProfileService;
import com.yuhong.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;


@RestController
@RequestMapping("/profile")
@Slf4j
public class ProfileController {

    @Resource
    private ProfileService profileService;

    @Resource
    private UserService userService;

    @Resource
    private UserProfileService userProfileService;


    @PostMapping("/uploadProfile")
    public BaseResponse<String> uploadProfile(@RequestParam("file") MultipartFile file, @RequestParam String userId ){

        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.lambda().eq(User::getUserAccount, userId);
        User one = userService.getOne(qw);

        String profileId = profileService.uploadProfile(file, one);

        return ResultUtils.success(profileId);

    }


    @GetMapping("/get/vo")
    public BaseResponse<ProfileVO> getProfileVOById(long id, HttpServletRequest request) throws JsonProcessingException {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Profile profile = profileService.getById(id);
        if (profile == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(profileService.getProfileVO(profile));
    }


    /**
     * 分页获取列表（封装类）
     *
     * @param profileQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ProfileVO>> listProfileVOByPage(@RequestBody ProfileQueryRequest profileQueryRequest,
                                                               HttpServletRequest request) {
        long current = profileQueryRequest.getCurrent();
        long size = profileQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Profile> postPage = profileService.page(new Page<>(current, size),
                profileService.getQueryWrapper(profileQueryRequest));
        return ResultUtils.success(profileService.getProfileVOPage(postPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param profileQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/vo")
    public BaseResponse<ProfileVO> listMyProfileVO(@RequestBody ProfileQueryRequest profileQueryRequest,
                                                             HttpServletRequest request) {
        if (profileQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
//        User loginUser = userService.getLoginUser(request);
//        postQueryRequest.setUserId(loginUser.getUserAccount());
        long current = profileQueryRequest.getCurrent();
        long size = profileQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        QueryWrapper<UserProfile> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserProfile::getUserId, profileQueryRequest.getUserId());
        UserProfile userProfile = userProfileService.getOne(queryWrapper);

        if(userProfile == null){
            return ResultUtils.error(50000, "未查询到数据");
        }
        String profileId = userProfile.getProfileId();
        QueryWrapper<Profile> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(Profile::getProfileId, profileId);
        Profile profile = profileService.getOne(queryWrapper1);

        ProfileVO profileVO = BeanUtil.copyProperties(profile, ProfileVO.class);

        return ResultUtils.success(profileVO);
    }

    /**
     * @description:编辑个人简历信息
     * @author: renyuhong
     * @date: 2025/5/4 11:13
     * @param: [profileEditRequest, request]
     * @return: com.yuhong.springbootinit.common.BaseResponse<java.lang.Boolean>
     **/
    @PostMapping("/edit")
    public BaseResponse<Boolean> editMyProfile(@RequestBody ProfileEditRequest profileEditRequest, HttpServletRequest request) {

        Long id = profileEditRequest.getId();

        Profile oldProfile = profileService.getById(id);
        if (oldProfile == null) {
            return ResultUtils.error(50010, "未查询到简历");
        }

        Profile profile = BeanUtil.copyProperties(profileEditRequest, Profile.class);
        boolean b = profileService.updateById(profile);

        return ResultUtils.success(b);
    }

    @GetMapping("/get/my/profile")
    public BaseResponse<Profile> getMyProfile(@RequestParam String userId){

        QueryWrapper<UserProfile> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserProfile::getUserId, userId);

        UserProfile userProfile = userProfileService.getOne(queryWrapper);
        if(userProfile == null){
            return ResultUtils.error(50011, "查询不到对应关系");
        }

        QueryWrapper<Profile> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(Profile::getProfileId, userProfile.getProfileId());
        Profile profile = profileService.getOne(queryWrapper1);

        return ResultUtils.success(profile);

    }


    @GetMapping("/preview/{filename}")
    public ResponseEntity<org.springframework.core.io.Resource> profilePreview(@PathVariable String filename) {
        try {
            String directoryPath = "E:\\resumes\\";
            File file = new File(directoryPath + filename);
            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }
            Path path = Paths.get(directoryPath, filename);
            org.springframework.core.io.Resource resource = new UrlResource(path.toUri());
            HttpHeaders headers = new HttpHeaders();
            String extension = FilenameUtils.getExtension(filename);
            if (extension.equals("pdf")) {
                headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);
            } else if (extension.equals("jpg")) {
                headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE);
            } else {
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"");
            }
            return ResponseEntity.ok().headers(headers).body(resource);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

}
